////////////////////////////////////////////// Document Preview ////////////////////////////////////////////
var TAB='  ';//xml text tab
var NEW_LINE='\n';//text line seperator

var slaPreview=new Ext.form.FormPanel({
	id:'slaPreview',
	//region:'east',
	layout : 'border',
	columnWidth:.5,
	height:400,
	//autoHeight: true,
	items:[
	{
    	id:'previewText',
    	region:'center',
    	xtype:'textarea',
    	autoScroll : true,
		border : true,
		height:400,
		name:'previewText'
    } 
	],
	buttons:[
	{
		xtype:'button',
		text:'预览/刷新',
		handler:function(){
			var pt=Ext.getCmp('previewText');	
			pt.setValue(getXml(sla_root,0));
		}
	},
	{
		xtype:'button',
		text:'保存',
		handler:function(){
			Ext.Msg.alert('消息','保存成功！');
		}
	}
	]
});


////////////////////////////////////////////// Tree ////////////////////////////////////////////
var sla_root=new Ext.tree.TreeNode({  
   id : "root",  
   text : "SLA",
   tag : "wsla:SLA",
   attributes : new HashMap(),
   children:[
   ]
});

var partiesNode=new Ext.tree.TreeNode({  
	id:"parties",
	text : "Parties",
	tag : "Parties",
	attributes : new HashMap(),
	listeners :{
		'contextmenu':function(node,e){
			tree.selectedNode=node;
			addPartyMenu.showAt(e.getXY());
		}
	}
});

var serviceDefinitionNode=new Ext.tree.TreeNode({  
	id:"serviceDefinition",
	text : "ServiceDefinition",
	tag : "ServiceDefinition",
	attributes : new HashMap(),
	listeners :{
		'contextmenu':function(node,e){
			tree.selectedNode=node;
			serviceDefinitionMenu.showAt(e.getXY());
		}
	}
});

var obligationsNode=new Ext.tree.TreeNode({  
	id:"obligations",
	text : "Obligations",
	tag : "Obligations",
	attributes : new HashMap()
});

var tree = new Ext.tree.TreePanel({
    autoScroll:true,  
    autoHeight:true,  
    animate:true,  
//    enableDD:true,  
//    loader: new Ext.tree.TreeLoader({  
//      dataUrl:'tree.do'     
//    }) ,
	initTree : function(){
		
		var attr=new HashMap();
		attr.put('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
		attr.put('xmlns:wsla', 'http://www.ibm.com/wsla');
		attr.put('name', slaPanel.name);
		sla_root.attributes.attributes=attr;
		
		sla_root.appendChild(partiesNode);
		sla_root.appendChild(serviceDefinitionNode);
		sla_root.appendChild(obligationsNode);
		
		tree.expandAll();	
	} ,
	root:sla_root,
	selectedNode:undefined
}); 

/////////////////////////////////////////////////// panel ///////////////////////////////////////////////////

var sla_editor = new Ext.Panel({
	id : "sla-editor-panel",
	text : "SLA编辑器",
	//region: 'center',
	columnWidth:.5,
	items : [
	    tree
	]
});



var slaPanel = new Ext.Panel({
	title : '添加SLA',
	id : 'sla-panel',
	layout : 'column',
	name:'',
	items : [
	    sla_editor,
	    slaPreview
	],
	showPage : function() {
		tree.initTree();
	}
}); 

//////////////////////////////////////////////right click menu ///////////////////////////////////////
var addPartyMenu = new Ext.menu.Menu({
	id : 'addPartyMenu',
	items : [ {
		//xtype : "button",
		text : "添加ServiceProvider",
		iconCls : "add",
		pressed : true,
		handler : function(){
			signatoryPartyPanel.form.reset();
			
			var type='SignatoryParty';
			var btn=signatoryPartyPanel.buttons[0];
			btn.setText('添加');
			btn.action='add';
			
			signatoryPartyWin.title='Service Provider Info';
			Ext.getCmp('signatory_party_type').setValue('ServiceProvider');
			
			signatoryPartyWin.show();
		}
	},{
		//xtype : "button",
		text : "添加ServiceConsumer",
		iconCls : "add",
		pressed : true,
		handler : function(){
			signatoryPartyPanel.form.reset();
			
			var type='SignatoryParty';
			var btn=signatoryPartyPanel.buttons[0];
			btn.setText('添加');
			btn.action='add';
			
			signatoryPartyWin.title='Service Consumer Info';
			Ext.getCmp('signatory_party_type').setValue('ServiceConsumer');
			
			signatoryPartyWin.show();
		}
	}, {
		//xtype : "button",
		text : "添加Supporting Party",
		iconCls : "edit",
		pressed : true,
		handler : function(){
			supportingPartyPanel.form.reset();
			
			var type='SupportingParty';
			var btn=supportingPartyPanel.buttons[0];
			btn.setText('添加');
			btn.action='add';
			
			supportingPartyWin.title='Supporting Party Info';
			
			supportingPartyWin.show();
		}
	}]
});

var serviceDefinitionMenu=new Ext.menu.Menu({
	id : 'serviceDefinitionMenu',
	items:[{
		//xtype : "button",
		text : "添加Schedule",
		iconCls : "add",
		pressed : true,
		handler : function(){
			schedulePanel.form.reset();
			
			var type='Schedule';
			var btn=schedulePanel.buttons[0];
			btn.setText('添加');
			btn.action='add';
			
			scheduleWin.show();
		}
	}
	,{
		//xtype : "button",
		text : "添加Metric",
		iconCls : "add",
		pressed : true,
		handler : function(){
			metricPanel.form.reset();
			
			var type='Metric';
			var btn=metricPanel.buttons[0];
			btn.setText('添加');
			btn.action='add';
			
			metricWin.show();
		}
	}
	,{
		//xtype : "button",
		text : "添加Trigger",
		iconCls : "add",
		pressed : true,
		handler : function(){
			triggerPanel.form.reset();
			
			var type='Trigger';
			var btn=triggerPanel.buttons[0];
			btn.setText('添加');
			btn.action='add';
			
			triggerWin.show();
		}
	}
	,{
		//xtype : "button",
		text : "添加Constant",
		iconCls : "add",
		pressed : true,
		handler : function(){
			constantPanel.form.reset();
			
			var type='Constant';
			var btn=constantPanel.buttons[0];
			btn.setText('添加');
			btn.action='add';
			
			constantWin.show();
		}
	}
	,{
		//xtype : "button",
		text : "添加SLAParameter",
		iconCls : "add",
		pressed : true,
		handler : function(){
			slaParameterPanel.form.reset();
			
			var type='SLAParameter';
			var btn=slaParameterPanel.buttons[0];
			btn.setText('添加');
			btn.action='add';
			
			slaParameterWin.show();
		}
	}
	]
});

/////////////////////////// SLA File Upload Window ////////////////////////////////
var slaUploadWin=new Ext.Window({
	id:'SLAUploadWIN',
	title:'上传SLA文件',
	closeAction:'hide',
	modal:true,
	closable:true,
	items:[
	{
		id : 'SLAUploadPanel',
		title : '文件列表',
		xtype : 'slauploadpanel',
		uploadUrl : 'uploadSLA.action',
		filePostName : 'myUpload', // 这里很重要，默认值为'fileData',这里匹配action中的setMyUpload属性
		flashUrl : 'uploaddialog/js/swfupload.swf',
		fileSize : '500 MB',
		height : 300,
		border : false,
//		bbar:[ 
//             '上传结果：',new Ext.form.TextArea({
//             name : 'otherResult',
//             id:'otherResult',
//             width:500,
//             fieldLabel : "上传结果"
//             })
//         ],
		fileTypes : '*.*', // 在这里限制文件类型:'*.jpg,*.png,*.gif'
		fileTypesDescription : '所有文件',
		postParams : {
			path : 'files\\' // 上传到服务器的files目录下面			                                  
		}
	}
	]
});



////////////////////  id generator  ///////////////////////
var IDgen=function(){
	this.id=0;
	this.newId=function(){
		return this.id++;
	}
};
var idgen=new IDgen();

//find child by tag
function findChildByTag(node,tag){
	var target=undefined;
	node.eachChild(function(child){
		if(child.tag==tag){
			target=child;
		}
	});
	return target;
}

//initiate form fields with a node
function initiateForm(node,form){
	var attr=node.attributes.attributes;
	var type=node.attributes.type==undefined?node.attributes.tag:node.attributes.type;
	if(attr!=undefined){
		var keys=attr.keys();
		for(var i=0;i<keys.length;i++){
			var key=keys[i];
			
			var field=form.form.findField(type.toLowerCase()+'_attr_'+key);
			if(field==undefined){
				continue;
			}else{
				field.setValue(attr.get(key));
			}
		}
	}	
	
	var content=type.toLowerCase()+'_content'
	var tag=form.form.findField(content);
	if(tag!=undefined){
		tag.setValue(node.attributes.content);
	}
	
	node.eachChild(function(child){
		initiateForm(child,form);
	});
}

//node operation menu
var nodeOperationMenu=new Ext.menu.Menu({
	id : 'nodeOperationMenu',
	items : [ {
		//xtype : "button",
		text : "编辑节点信息",
		iconCls : "edit",
		pressed : true,
		handler : function(){
			var node=tree.selectedNode;
			var type=node.attributes.type;
			if(type==undefined){
				type=node.attributes.tag;
			}
			var form=Ext.getCmp(type+'Panel');
			form.form.reset();
			
			var btn=form.buttons[0];
			btn.setText('编辑');
			btn.action='edit';
			
			initiateForm(node,form);
			var win=Ext.getCmp(type+'Win');
			win.show();
		}
	},{
		//xtype : "button",
		text : "删除节点",
		iconCls : "delete",
		pressed : true,
		handler : function(){
			var node=tree.selectedNode;
			node.remove();
		}
	}]
});

//generate xml text by a tree or node 
function getXml(node,depth){
	if(depth==undefined){
		depth=0;
	}
	var xml='';
	var tab='';
	for(var i=0;i<depth;i++){
		tab+=TAB;
	}
	//print tag start
	var tag=node.attributes.tag;
	xml+=tab+'<'+tag;
	
	//print attributes
	var attr=node.attributes.attributes;
	if(attr!=undefined){
		var keys=attr.keys();
		for(var i=0;i<keys.length;i++){
			var key=keys[i];
			xml+=' '+key+'=\''+attr.get(key)+'\'';
		}
	}
	
	xml+='>'+NEW_LINE;
	
	if(node.attributes.content!=undefined){
		//print node text content		
		xml+=tab+TAB+node.attributes.content+NEW_LINE;
	}else{
		//print all child nodes of the tree
		node.eachChild(function(child){
			var childXml=getXml(child,depth+1);
			xml+=childXml;
		});
	}
	
	//print tag end
	xml+=tab+'</'+tag+'>'+NEW_LINE;
	
	return xml;
}
